<?php


namespace App\Services\Core\Traits;

use App\Exceptions\ErrResponse;

trait Validator
{
    # 验证结果
    public $validRes;
    # 错误号
    public int $validStatus = 412;
    # 字段规则
    protected array $rules = [];
    # 字段提示
    protected array $tips = [];
    # 验证数据
    private array $data = [];

    protected function chkMobile(string $mobile): bool
    {
        return preg_match("/^1[3456789]\d{9}$/", $mobile);
    }

    protected function chkEmail(string $account): bool
    {
        return in_array(substr($account, strripos($account, "@")),$this->getEmailMain());
    }

    protected function getEmailMain(array $email = ['@163.com', '@qq.com', '@gmail.com']): array
    {
        return $email;
    }

    protected function verify()
    {
        try {
            $this->request->validate($this->rules);
        } catch (\Exception $exception) {
            $this->validRes = array_intersect_key($this->tips, $exception->errors());
        }
        return $this->validRes;
    }

    public function unsetRules(...$unsetFields)
    {
        $this->setRules();

        foreach ($unsetFields as $key => $item) unset($this->tips[$item], $this->rules[$item]);

        return $this;
    }

    protected function validExit()
    {
        $this->verify();
        if ($this->validRes) {
            throw new ErrResponse(json_encode([
                'status' => $this->validStatus,
                'code'   => 20000,
                'msg'    => '验证失败',
                'result' => $this->validRes,
            ]));
        }
    }

    protected function getRules(...$fields)
    {
        $rules = [];
        $tips  = [];

        $this->setRules();

        foreach ($fields as $key => $item) {
            $tips[$item]  = $this->tips[$item];
            $rules[$item] = $this->rules[$item];
        }

        $this->tips  = $tips;
        $this->rules = $rules;

        return $this;
    }


    protected function setValidData(array $data)
    {
        $this->data = $data;
        return $this;
    }

    protected function setRules()
    {
    }

}
